package user;

import utils.JsonOut;
import utils.MysqlUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@WebServlet(name = "FollowServlet")
public class FollowServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();

        String email = UserSession.getUserSessionEmail(session);

        PrintWriter out = response.getWriter();
        if (email == null || email.isEmpty()){
            out.println(JsonOut.error(220, "not_login"));
            return;
        }

        String userId = request.getParameter("user_id");

        // 检查字段
        if (userId == null || userId.isEmpty()){
            out.println(JsonOut.error(201, "no_user_id"));
            return;
        }

        // 判断是否已关注
        String followStatus = (new MysqlUtils()).getFollowStatus(email, userId);
        if (followStatus.equals("followed") || followStatus.equals("friend")){
            HashMap<String, String> data = new HashMap<>();
            data.put("follow_state", followStatus);
            out.println(JsonOut.common(0, "followed", data));
            return;
        }

        if (!(new MysqlUtils()).addFollowUser(email, userId)){
            out.println(JsonOut.error(500, "sql_sth_wrong"));
            return;
        }

        followStatus = (new MysqlUtils()).getFollowStatus(email, userId);
        HashMap<String, String> data = new HashMap<>();
        data.put("follow_state", followStatus);

        out.println(JsonOut.common(0, "follow_success", data));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println(JsonOut.error(403, "forbidden"));
    }
}
